# coding = utf-8
import numpy as np
import cv2 as cv
import matplotlib.pyplot as plt

def unpackOctave(keypoint):
    """Compute octave, layer, and scale from a keypoint
    """
    octave = keypoint.octave & 255
    layer = (keypoint.octave >> 8) & 255
    if octave >= 128:
        octave = octave | -128
    scale = 1 / np.float32(1 << octave) if octave >= 0 else np.float32(1 << -octave)
    return octave, layer, scale

# 导入资源
image = cv.imread(r'D:\data\CUGW-test\20230819left2\tmp\tmp.JPG')
image_copy = np.copy(image)
image_copy = cv.cvtColor(image_copy, cv.COLOR_BGR2RGB)
img_gray = cv.cvtColor(image_copy, cv.COLOR_RGB2GRAY)
gray = np.float32(img_gray)

# SIFT角点检测
sift = cv.SIFT_create(500)
# 找到关键点和描述符
# maskRight2 = np.zeros(image.shape[0:2],dtype="uint8")   #maskRight
# cv.rectangle(maskRight2,(0,0),(int(image.shape[1]*2/3),image.shape[0]),255,-1)
# maskAll = maskRight2#cv2.bitwise_and(maskTop,maskRight2)
# cv.imwrite('out/maskAll.jpg', maskAll)
keypoints, des = sift.detectAndCompute(img_gray, None)

#统计各层特征点个数
counts = {}
for kp in keypoints:
    kpr = unpackOctave(kp)
    counts[kpr[2]] = counts.get(kpr[2],0) + 1
counts2 = sorted(counts.items(),key=lambda x: x[0], reverse=False)
print(counts2)
#[(-1, 352), (0, 134), (1, 14)]
#[(1, 213), (2, 180), (3, 107)]
#[(0.5, 14), (1.0, 134), (2.0, 352)]
#[(0.5, 21), (1.0, 185), (2.0, 295)]#cv.SIFT_create(500,6)

# 把特征点标记到图片上
corner_image = cv.cvtColor(img_gray, cv.COLOR_GRAY2RGB)#np.copy(image_copy)
for point in keypoints:
    cv.circle(corner_image, (int(point.pt[0]), int(point.pt[1])), 6, (0,255,0), 3)
cv.imwrite('out/SIFT2.jpg', corner_image)
plt.imshow(corner_image)
plt.show()